package com.wxxymakers.cklabrecruit.controller;

import com.wxxymakers.cklabrecruit.entity.User;
import com.wxxymakers.cklabrecruit.entity.enum_.Role;
import com.wxxymakers.cklabrecruit.service.UserService;
import com.wxxymakers.cklabrecruit.utils.RestResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.pam.UnsupportedTokenException;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

/**
 * @AUTHOR soft
 * @DATE 2018/11/5 23:21
 * @DESCRIBE
 */
@RestController
public class UserController {

    private final UserService service;

    @Autowired
    public UserController(UserService service) {
        this.service = service;
    }

    /**
     * 用户登录
     * @param user 用户
     * @param remember 是否记住密码
     */
    @PostMapping("/login")
    public RestResponse login(User user,
                              @RequestParam(defaultValue = "", required = false) Boolean remember) {
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword(), remember);
        Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            return RestResponse.fail("用户名不存在！");
        } catch (UnsupportedTokenException e) {
            return RestResponse.fail("密码错误！");
        } catch (AuthenticationException e) {
            return RestResponse.fail("登录失败！");
        }
        return RestResponse.ok("登录成功！");
    }

    /**
     * 用户注册只能注册学生
     * @param user 用户信息
     */
    @PostMapping("/register")
    public RestResponse register(User user) {
        user.setRole(Role.STUDENT);
        User add = service.add(user);
        if (add != null) {
            return RestResponse.ok("注册成功！");
        }
        return RestResponse.fail();
    }

    /**
     * 分页查询
     * @param no 页码
     * @param size 尺寸
     * @param user 查询条件
     */
    @RequiresRoles("admin")
    @PostMapping("/page/{no}")
    public RestResponse page(@PathVariable Integer no,
                             @RequestParam(defaultValue = "10", required = false) int size,
                             User user) {
        Page<User> page = service.getPage(no, size, user);
        if (page != null) {
            return RestResponse.ok(page);
        }
        return RestResponse.fail();
    }
}
